<template>
  <div class="goods_detail">
    <van-sticky>
      <div class="header">
        <div class="header_title">多开分身商城</div>
        <div class="home" @click="backHome">
          <img src="@/assets/img/home.png" alt="">
        </div>
      </div>
    </van-sticky>
    <div class="content">
      <div class="title"></div>
      <div class="desc">
        <div class="top">
          <div class="topleft">
            <img :src="currentSwiper.image" alt="">
          </div>
          <div class="topright">
            <div class="name_sales">
              <span class="name">{{ currentSwiper.name }}</span>
              <span class="sales" v-if="currentSwiper.salesNum">销量{{ currentSwiper.salesNum }}</span>
            </div>
            <div class="advanage">
              <span class="one" v-if="labels[0]">
                {{labels[0]}}
              </span>
              <span class="two" v-if="labels[1]">
                {{labels[1]}}
              </span>
            </div>
            <div class="price">
              <span style="color: #666;font-size: 12px;">商品单价：</span>
              <span style="color: #FF0000; font-size: 11px;">￥</span>
              <span style="color: #FF0000; font-size: 16px; font-weight: 400;">{{ currentSwiper.price }}</span>
            </div>
          </div>
        </div>

      </div>
      <van-radio-group v-model="payWay">
        <van-cell-group>
          <van-cell title="支付宝支付" clickable @click="payWay = 'alipayh5'">
            <template #icon>
              <img style="width: 18px;height: 18px;" src="@/assets/img/alipay.png" alt="">
            </template>
            <template #right-icon>
              <van-radio name="alipayh5" />
            </template>
          </van-cell>
          <!-- <van-cell title="微信支付" clickable @click="payWay = 'wxpayh5'">
            <template #icon>
              <img style="width: 18px;height: 18px;" src="@/assets/img/wxpay.png" alt="">
            </template>
            <template #right-icon>
              <van-radio name="wxpayh5" />
            </template>
          </van-cell> -->
          
        </van-cell-group>
      </van-radio-group>
      <div class="input_area">
        <div class="phoneormail">
          <van-field
              id="phone"
              v-model="phone_email"
              label="手机号码/邮箱"
              placeholder="下单需要输入您的手机号码或邮箱"
              label-align="top"
              style="padding: 0;margin-bottom: 10px;"
          />
          <!-- <van-tag plain class="hover" type="primary" @click="getUDID('1')" >点击此处获取您的UDID序列号</van-tag>
          <van-tag plain class="hover" type="primary" style="margin-left: 15px;" @click="getUDIDVideo">获取视频教程</van-tag> -->
        </div>
      </div>
      <div class="tips">
        <div class="important">
          商家提醒：请填写手机号后下单，手机号，仅用于查询订单
        </div>
        <div>付款后，下载链接都会在付款成功后显示。若有问题可联系客服一对一服务！</div>
      </div>
      <div class="goods_ind" style="margin-top: 15px">
        <div class="goods_tit" style="font-size: 16px;font-weight: 500;color: #333;margin-bottom: 4px;">
          商品介绍
        </div>
        <div class="24hours" style="font-size: 15px;font-weight: 500;color: #333;margin-bottom: 8px;">24小时自助下单：<span style="color: #FF0000;font-weight: 500;">兼容苹果所有系统</span></div>
        <div style="font-size: 13px;color: #333;line-height: 20px;">购买成功后您将获得：<span style="font-size: 13px;color: #FF0000;font-weight: 500;">下载链接、安装教程、VIP客服联系方式</span></div>
      </div>
      <div class="about_program">
        <div style="font-weight: 500;">关于软件：</div>
        <div style="font-weight: 500;">【官方有的功能它都有】【同步最新8.0.40以上版本】</div>
        <div>推荐日常使用；稳定不掉签，纯净无广告，无需越狱，安装方便</div>
      </div>
      <div class="about_usetime">
        <div style="font-weight: 500;">关于使用时间：</div>
        <div>激活码是永久的，使用没有时间限制，不用续费，只要开发商在市就一直可以使用，开发商退市才用不了。本平台不卖垃圾软件，客服全天在线任何问题都可咨询！</div>
      </div>
      <div class="about_afterSales">
        <div style="font-weight: 500;">关于售后保障服务和注意事项：</div>
        <div>购买成功后：下载地址和激活码保存好，务必添加客服联系方式；</div>
        <p>
          本店售卖的是激活码，不参与软件开发与制作，软件仅供娱乐，不得用于非法用途；
        </p>
        <p>购买软件都送保障服务，保障期间内软件出现问题联系客服进行技术协助备份聊天记录和更换软件即可；</p>
        <p>软件下载成功后，只能用于登陆，禁止注册账号（注册请用官方的注册）；</p>
        <p>激活码为虚拟产品，不支持无理由退换货（不能下载使用除外）；</p>
      </div>
      <div class="advantage">
        <img src="@/assets/img/advantage.png" alt="">
      </div>
      <div style="margin-bottom: 2px;">
        <span class="title1">公司名称：</span>
        <span class="content1">{{ company.name }}</span>
      </div>
      <div style="margin-bottom: 2px;">
        <span class="title1">联系人：</span>
        <span class="content1">{{company.contacts}}</span>
      </div>
      <div style="margin-bottom: 2px;">
        <span class="title1">联系地址：</span>
        <span class="content1">{{ company.contact_address }}</span>
      </div>
      <div style="margin-bottom: 15px;">
        <span class="title1">联系方式：</span>
        <span class="content1">{{ company.contact_us }}</span>
      </div>
      <div class="buy_button" @click="createOrder">
        <span style="font-size: 16px;">￥</span>
        <span style="font-size: 24px;">{{currentSwiper.showPrice}}</span>
        <span style="font-size: 18px;"> 立即购买</span>
      </div>
      <div class="seek_order kefu" @click="seekOrder">
        <img src="@/assets/img/order.png" alt="">
      </div>
      <div class="seek_order" @click="kefu">
        <img src="@/assets/img/seek.png" alt="">
      </div>


    </div>
  </div>
  <van-dialog v-model:show="show" title="请填写您的UDID序列号" show-cancel-button @confirm="updateUDID" @cancel="dialogClose" :before-close="beforeClose">
    <van-field
      v-model="dialog_udid"
      label=""
      placeholder="请输入您的UDID序列号"
      label-align="top"
    />
    <van-tag plain class="hover" type="primary" @click="getUDID('2')" style="margin: 10px 15px">点击此处获取您的UDID序列号</van-tag>
  </van-dialog>

</template>

<script setup lang="ts">

import { useRouter,useRoute } from "vue-router";
import { onBeforeUnmount, onMounted, onUnmounted, ref } from "vue";
import Request from '@/utils/axios';
import { showLoadingToast, closeToast, showNotify,showSuccessToast,showFailToast } from 'vant';

const router = useRouter()
const route = useRoute()
let phone_email = ref('');
let udid = ref('');
let startTime:number;
let endTime:number;
const currentSwiper = ref<any>({})
const payWay = ref('alipayh5');
let productId = ref()
let queryCount = 0; // 定义一个计数器，用于记录查询次数
const maxQueries = 60; // 2分钟内可以查询60次（每2秒一次）
const intervalTime = 2000; // 每隔2秒查询一次
let intervalId:any; // 定义定时器ID
let show = ref<boolean>(false);
let dialog_udid = ref<string>('')
let is_close = ref<boolean>(false) // 弹框是否关闭
let udidLink:string // 获取udid链接
let labels = ref<any[]>([])
const company = ref<any>({})
// 跳转UDID链接
const getUDID = (type:string) => {
  // window.open(udidLink,'_blank');
  window.location.href = udidLink
  if (type == '1') {
    show.value = true;
  }
}
const getUDIDVideo = () => {
  // window.open('https://cdn.yicsucc.com/appletools/other/8458_1733301147.mp4','_blank');
  window.location.href = 'https://cdn.yicsucc.com/appletools/other/8458_1733301147.mp4'
}
// 获取商品列表
const getGoodsList = () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  Request.get('/goods').then((res:any) => {
    console.log(res);
    if (res.data) {
      let data = res.data
      data.forEach((ele:any) => {
        if (ele.id == productId.value) {
          currentSwiper.value = ele;
        }
      })
      
      console.log(currentSwiper.value);
      labels.value = currentSwiper.value.labels
      closeToast()
    }
  })
}

const backHome = () => {
  router.push('/goods')
}

// 查订单按钮
const seekOrder = () => {
  router.push('/order')
}
// 咨询按钮
const kefu = () => {
  // window.open('https://work.weixin.qq.com/kfid/kfcc29d7dfa36a355f6','_blank')
  window.location.href = 'https://work.weixin.qq.com/kfid/kfcc29d7dfa36a355f6'
}
// 创建订单
const createOrder= ()=> {
  if (phone_email.value.trim() == "") {
    showNotify({ type: 'warning', message: '请输入您的手机号码或邮箱', duration: 1500 });
    return;
  }
  let formData = new FormData()
  formData.append('goodsId',currentSwiper.value.id)
  formData.append('payPrice',currentSwiper.value.price)
  formData.append('payType',payWay.value)
  formData.append('source','web')
  formData.append('phone',phone_email.value)
  formData.append('bundleId','')
  formData.append('goodsType',currentSwiper.value.goodsType)
  formData.append('couponId','')
  Request.post('/order',formData).then((res:any) => {
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
    })
    if (res.code == 0) {
      let data = res.data;
      console.log(data);
      // return
      if (payWay.value == 'alipayh5') {
        var link = document.createElement('a');
        link.href = payWay.value == 'alipayh5' ? data.payParam : data.wxpayH5Url;
        link.target = '_blank';
        document.body.appendChild(link);
        setTimeout(() => {
          link.click();
          document.body.removeChild(link);
          // window.open(payWay.value == 'alipayh5' ? data.payParam : data.wxpayH5Url,'_blank')
          window.location.href = payWay.value == 'alipayh5' ? data.payParam : data.wxpayH5Url
          closeToast()
        },500)
        startCheckingOrder(data.orderId)
      } else {
        // 微信支付根据订单ID获取重定向支付链接
        // setTimeout(() => {
          // window.open(`${ConfigUrl.serveURL}/order/wx/h5?orderId=${data.orderId}`,'_blank')
        // },500)
        // startCheckingOrder(data.orderId)
      }
      
    }
  })
}

// 定义查询订单状态
function checkOrderStatus(orderId:any) {
  return new Promise((resolve, reject) => {
    Request.get(`/order/status?orderId=${orderId}`).then((res:any) => {
      const isPaid = res.data.status == 2
      resolve(isPaid)
    })
  });
}

// 开始查询
function startCheckingOrder(orderId:any) {
  console.log('orderId');
  let hasPaid = false;

  // 设置一个总的超时时间，确保2分钟后停止查询
  const timeoutId = setTimeout(() => {
    clearInterval(intervalId); // 清除间隔查询
    if (!hasPaid) {
      showFailToast('支付失败');
      queryCount = 0
    }
  }, 2 * 60 * 1000); // 2分钟

  // 使用setInterval每2秒查询一次
  intervalId = setInterval(async () => {
    try {
      const isPaid = await checkOrderStatus(orderId);
      console.log(isPaid);
      if (isPaid) {
        clearInterval(intervalId); // 如果支付成功，清除间隔查询
        clearTimeout(timeoutId); // 清除总的超时
        hasPaid = true;
        showSuccessToast('支付成功');
        queryCount = 0
        // setTimeout(() => {
        //   closeToast()
        //   show.value = true;
        // },1000)
      }
    } catch (error) {
      showFailToast('查询订单状态时发生错误:');
    }
    // 更新查询计数器
    queryCount++;
    if (queryCount >= maxQueries) {
      clearInterval(intervalId); // 达到最大查询次数后停止查询
      clearTimeout(timeoutId); // 清除总的超时
      if (!hasPaid) {
        showFailToast('支付失败');
        queryCount = 0
      }
    }
  }, intervalTime);
}
// 更新用户信息
const updateUDID = () => {
  if (dialog_udid.value.trim() == ""){
    is_close.value = false
    return;
  }
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  let params = {
    udid: dialog_udid.value
  }
  Request.put('/user',params).then((res:any) => {
    if (res.code === 0) {
      closeToast()
      show.value = false;
      is_close.value = true
      dialog_udid.value = '';
      showSuccessToast('操作成功')
    }
  })
}
// 弹框关闭
const dialogClose = () => {
  dialog_udid.value = ''
  show.value = false
}

const beforeClose = (action:any) => {
  if (action == 'confirm') {
    if (is_close.value) {
      show.value = false
    }
  } else {
    show.value = false
  }
}
onMounted(()=> {
  console.log(route);
  productId.value = route.query.id;
  document.getElementById('phone')?.addEventListener('focus', function() {
    this.scrollIntoView({ behavior: 'smooth', block: 'center' });
  })
  startTime = Date.now(); // 记录进入页面的时间
  let token = localStorage.getItem('duokai_token')
  Request.get(`/launch`).then((res:any) => {
    if (res.data) {
      company.value = res.data.config["client.company.info"]
      udidLink = res.data.config["client.user.udid.url"]
    }
  })
  getGoodsList()
    

  
})

onBeforeUnmount(() => {
  document.getElementById('phone')?.removeEventListener('focus', function() {
  })
})

onUnmounted(() => {
  endTime = Date.now(); // 记录离开页面的时间
  const duration = Math.round((endTime - startTime) / 1000); // 计算停留时间（秒）
  const formData = new FormData()
  formData.append('time',duration + '')
  Request.post('/stop',formData).then(res => {
    console.log(res);
  })
});

</script>

<style lang="less">
.goods_detail {
  width: 100%;
  background: #fff;
  padding-bottom: 50px;

  .header {
    height: 51px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #146DC9;
    padding: 0 15px;
    .header_title {
      font-weight: 500;
      font-size: 18px;
      color: #FFFFFF;
    }
    .home {
      height: 32px;
      width: 32px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .content {

    border-radius: 10px 10px 0 0;
    padding: 0 4.8%;
    .title {
      font-size: 18px;
      margin-top: 20px;
      margin-bottom: 10px;
      text-align: center;
    }
    .desc {
      box-sizing: border-box;
      width: 100%;
      .top {
        display: flex;
        .topleft {
          img {
            width: 46px;
            height: 46px;
            border-radius: 8px;
          }
        }
        .topright {
          margin-left: 9px;
          .name_sales {
            display: flex;
            align-items: center;
            .name {
              font-weight: 500;
              font-size: 15px;
              color: #333333;
            }
            .sales {
              margin-left: 7px;
              background-color: rgba(6, 196, 98, 0.08);
              color: #06C462;
              padding: 2px 8px;
              font-size: 10px;
              border-radius: 3px;
            }
          }
          .advanage {
            margin-top: 5px;
            margin-bottom: 10px;
            display: flex;
            .one{
              background-color: rgba(30, 0, 255, 0.05);
              color: #1E00FF;
              padding: 2px 8px;
              font-size: 10px;
              border-radius: 3px;
            }
            .two {  
              padding: 2px 8px;
              font-size: 10px;
              border-radius: 3px;
              margin-left: 7px;
              background-color: rgba(255, 81, 0, 0.05);
              color: #FF5100;
            }
          }
        }
      }
    }
    .van-cell-group {
      display: flex;
      margin-top: 15px;
      .van-cell {
        align-items: center;
        img {
          margin-right: 8px;
        }
      }
    }
    .input_area {
      margin-top: 12px;
    }
    .tips {
      margin-top: 12px;
      font-size: 13px;
      .important {
        color: #FF0000;
        font-weight: 500;
      }
      div {
        margin-top: 6px;
        line-height: 19px;
      }
    }
    .about_program {
      margin-top: 9px;
      div:first-child {
        color: #FF0000;
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 3px;
      }
      div:nth-child(2) {
        color: #333;
        font-size: 13px;
        font-weight: bold;
      }
      div:nth-child(3) {
        color: #333;
        font-size: 13px;
      }
    }
    .about_usetime {
      margin-top: 9px;
      div:first-child {
        color: #FF0000;
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 3px;
      }
      div:nth-child(2) {
        color: #333;
        font-size: 13px;
      }
    }
    .about_afterSales {
      margin-top: 9px;
      div:first-child {
        color: #FF0000;
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 3px;
      }
      div:nth-child(2) {
        color: #333;
        font-size: 13px;
        margin-bottom: 5px;
      }
      p {
        color: #333;
        font-size: 13px;
        margin-bottom: 5px;
      }
    }
    .advantage {
      margin: 15px 0;
      img {
        width: 100%;
        height: 322.28px;
      }
    }
    .buy_button {
      position: fixed;
      bottom: 4px;
      width: 88%;
      height: 45px;
      background: linear-gradient( 313deg, #40CDCF 0%, #4F8FFB 100%);
      box-shadow: 0px 4px 10px 0px rgba(72,175,229,0.42);
      border-radius: 40px 40px 40px 40px;
      color: #fff;
      line-height: 45px;
      text-align: center;
      font-size: 18px;
    }
    .seek_order {
      position: fixed;
      right: 4.8%;
      bottom: 62px;
      img {
        width: 70px;
        height: 70px;
      }
    }
    .kefu {
      bottom: 145px;
    }
    .hover:active{
      border-color: #1367BC;
      color: #1367BC;
    }
    .title1 {
      font-size:13px;
      font-weight:500;
      color: #333;
      
    }
    .content1 {
      font-weight:500;
      font-size: 13px;
      color: #333;
    }
  }
}
</style>